package com.tsd.system.service.impl;

import com.tsd.CommonMsgNameConstants;
import com.tsd.core.constants.Constants;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.HlpException;
import com.tsd.core.vo.PageBean;
import com.tsd.service.BaseServiceImpl;
import com.tsd.system.dao.SysGroupMapper;
import com.tsd.system.dao.SysGroupPersonMapper;
import com.tsd.system.entity.SysGroup;
import com.tsd.system.entity.SysGroupExt;
import com.tsd.system.entity.SysUser;
import com.tsd.system.service.SysGroupService;
import com.tsd.system.utils.SysTreeUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 描述：SysGroup 服务实现层
 *
 * @author Hillpool
 * @date 2019/03/12 12:20:51
 */
@Service
public class SysGroupServiceImpl extends BaseServiceImpl implements SysGroupService {

    @Resource
    private SysGroupMapper sysGroupMapper;
    @Resource
    private SysGroupPersonMapper sysGroupPersonMapper;

    @Override
    public SysGroup getSysGroupById(Long id) throws Exception {
        return sysGroupMapper.selectByPrimaryKey(id);
    }

    @Override
    public SysGroupExt getSysGroupBySid(String sid) throws Exception {
        return sysGroupMapper.selectBySid(sid);
    }


    @Override
    public SysGroupExt queryBySid(String sid) throws Exception {
        return sysGroupMapper.selectBySid(sid);
    }

    @Override
    public void saveSysGroup(SysGroup record, SysUser sysUser) throws Exception {
        if (HlpUtils.isEmpty(record.getId())) {
            super.checkEmpty(record.getName(), "名称不能为空");
            super.autoInjectBaseData(record, sysUser, super.TYPE_CREATE);
            sysGroupMapper.insertSelective(record);
            sysGroupMapper.updateByPrimaryKeySelective(record);
        } else {
            super.autoInjectBaseData(record, sysUser, super.TYPE_UPDATE);
            sysGroupMapper.updateByPrimaryKeySelective(record);
        }
        if (!HlpUtils.isEmpty(record.getName())) {
            int num = sysGroupMapper.countByParentSidAndName(record.getParent_sid(), record.getName());
            if (num > 1) {
                throw new HlpException("部门名称重复，请重新输入！");
            }
        }
        this.updateChildCount(record.getParent_sid());
        this.setFullCode(record);
    }

    @Override
    public void deleteSysGroup(List<String> list, SysUser sysUser) throws Exception {
        for (String sid : list) {
            SysGroup group = this.queryBySid(sid);
            super.checkEmpty(group, CommonMsgNameConstants.ERROR_MSG_RECORD_NOT_EXISTS);
            List<SysGroupExt> sysGroupList = sysGroupMapper.selectByParentSid(group.getSid());
            if (sysGroupList != null && !sysGroupList.isEmpty()) {
                throw new HlpException(group.getName() + " 存在下级部门，请先删除下级部门再删除本部门");
            }
            deleteRelation(group, sysUser);
        }
    }

    /**
     * 删除子项
     *
     * @param group
     * @param sysUser
     */
    private void deleteRelation(SysGroup group, SysUser sysUser) {
        sysGroupMapper.deleteByPrimaryKey(group.getId());
        // 删除关联的客户
        sysGroupPersonMapper.deleteByGroupSid(group.getSid());
        List<SysGroupExt> childrens = sysGroupMapper.selectByParentSid(group.getSid());
        if (!childrens.isEmpty()) {
            for (SysGroup sysGroup : childrens) {
                deleteRelation(sysGroup, sysUser);
            }
        }
    }

    @Override
    public List<SysGroupExt> findSysGroups(Map<String, Object> params, PageBean page) throws Exception {
        return sysGroupMapper.selectByPage(params, page);
    }

    @Override
    public List<SysGroupExt> findSysGroups(Map<String, Object> params) throws Exception {
        return sysGroupMapper.selectByParams(params);
    }

    @Override
    public List<SysGroupExt> findSysGroupTree(Map<String, Object> params) throws Exception {
        String parentSid = HlpUtils.getString(params, "parent_sid");
        if (!HlpUtils.isEmpty(parentSid)) {
            SysGroup sysGroup = sysGroupMapper.selectBySid(parentSid);
            params.put("full_code", sysGroup.getFull_code() + "%");
        }
        params.remove("parent_sid");
        List<SysGroupExt> list = sysGroupMapper.selectByParams(params);
        return SysTreeUtil.expandSysGroupTree(list);
    }

    /**
     * 设置资源完整编码
     *
     * @param record
     */
    private void setFullCode(SysGroup record) {
        if (HlpUtils.isEmpty(record.getParent_sid())) {
            record.setFull_code(record.getId() + ".");
        } else {
            SysGroup parent = sysGroupMapper.selectBySid(record.getParent_sid());
            if (parent != null) {
                record.setFull_code(parent.getFull_code() + record.getId() + ".");
            } else {
                record.setFull_code(record.getId() + ".");
            }
        }
        sysGroupMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 设置下级资源数量
     *
     * @param sid
     */
    private void updateChildCount(String sid) {
        if (!HlpUtils.isEmpty(sid)) {
            SysGroup parent = sysGroupMapper.selectBySid(sid);
            if (parent != null) {
                int count = sysGroupMapper.countByParentSid(parent.getSid());
                parent.setChildren_count(count);
            }
        }
    }

}
